package nc.bs.io.util;

import nc.bs.common.util.FileSuffix;
import nc.bs.logging.Logger;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author duanyp1
 * @date 2023/11/1 18:38
 */
public class PropertiesUtil {

    private static long lastRecord;
    private static final long interval = 1000 * 60 * 5;
    private static final String suffix = FileSuffix.properties;
    public static final Map<String, Long> modify_record = new HashMap<>();

    public static File readFile(Class<?> clazz, String fileName) {
        return FileUtil.readFile(clazz, fileName, suffix);
    }

    public static boolean needUpdate(Class<?> clazz, String fileName) {
        long currentTimeMillis = System.currentTimeMillis();
        boolean timeInterval = (currentTimeMillis - lastRecord) > interval;
        if (timeInterval) {
            lastRecord = currentTimeMillis;
        }
        return timeInterval && needUpdate(readFile(clazz, fileName));
    }

    public static boolean needUpdate(File file) {
        String absolutePath = file.getAbsolutePath();
        long lastModified = file.lastModified();
        long lastRecord = modify_record.getOrDefault(absolutePath, lastModified);
        boolean needUpdate = lastRecord < lastModified;
        if (needUpdate) {
            modify_record.put(absolutePath, lastModified);
        }
        return needUpdate;
    }

    public static Properties getProperties(Class<?> clazz, String fileName) {
        Properties properties = new Properties();
        try (FileReader fileReader = new FileReader(readFile(clazz, fileName))) {
            properties.load(fileReader);
        } catch (IOException e) {
            Logger.error(e);
            throw new RuntimeException(e);
        }
        return properties;
    }


}
